package com.chezhujie.www.service;

import com.alibaba.fastjson.JSONObject;
import com.chezhujie.www.core.StaticMap;
import com.chezhujie.www.domain.Czjrecommendpic;
import com.chezhujie.www.domain.Czjweixininfo;
import com.chezhujie.www.domain.vo.WeixinInfo;
import com.chezhujie.www.persistence.RecommendpicMapper;
import com.sys.core.page.Pagination;
import com.sys.core.utils.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 汤伟杰 on 2017/5/15.
 */
@Service
public class RecommendpicService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RecommendpicMapper recommendpicMapper;
    @Autowired
    private WeixininfoService weixininfoService;
    private Map<String, Object> template;

    public Pagination list(int pageNo, int pageSize, String q, ModelMap model){
        try {
            autoEnter();
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("msg", "自动加载新微信用户出错！");
        }
        if(pageSize==0){
            pageSize = 20;
        }
        //得到弹出推荐图片模板
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listmap = jdbcTemplate.queryForList("select * from czj_xy_dataresource where code='TCMB'");
        for (Map<String, Object> objectMap : listmap) {
            map.put(String.valueOf(objectMap.get("name")),objectMap.get("value"));
        }
        Pagination pagination = new Pagination();
        pagination.setPageNo(pageNo);
        pagination.setPageSize(pageSize);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("q",q);
        param.putAll(pagination.toMap());
        int count = recommendpicMapper.getTotalRows(param);
        pagination.setTotalCount(count);
        List<Map<String, Object>> list = recommendpicMapper.getList(param);
        for (int i = 0; i < list.size(); i++) {
            if("1".equals(String.valueOf(list.get(i).get("usetemplate")))){
                list.get(i).put("picPath",map.get("picPath"));
                list.get(i).put("title",map.get("title"));
                list.get(i).put("url",map.get("url"));

            }
            if(null!=map.get("display")&&"0".equals(String.valueOf(map.get("display")))){
                list.get(i).put("display",0);
            }
        }
        pagination.setList(list);
        return pagination;
    }

    private void autoEnter() throws Exception {
        //得到Czjrecommendpic表中不存在关联微信的数据并新增
        List<Map<String, Object>> listMap = jdbcTemplate.queryForList("select wi.* from czj_weixininfo wi " +
                "LEFT JOIN czj_xy_recommendpic rp on rp.openid=wi.openid " +
                "where rp.recommendpicId is NULL");
        //得到Czjrecommendpic默认模板
        List<Czjrecommendpic> list = new ArrayList<Czjrecommendpic>();
        for (Map<String, Object> map : listMap) {
            Czjrecommendpic czjrecommendpic = new Czjrecommendpic();
            czjrecommendpic.setCreatetime(new Date());
            czjrecommendpic.setDisplay(1);
            czjrecommendpic.setOpenid(String.valueOf(map.get("openid")));
            czjrecommendpic.setUsetemplate(1);
            czjrecommendpic.setPicPath(null);
            czjrecommendpic.setRecommendpicId(UUIDUtils.getUUID());
            czjrecommendpic.setUrl(null);

            list.add(czjrecommendpic);
        }
        if(list.size()>0){
            recommendpicMapper.saves(list);
//            resourceDao.batchInsert(list);
        }


    }

    public void getDetail(String id, ModelMap model) throws Exception {
        Map<String, Object> map = jdbcTemplate.queryForMap("select * from czj_xy_recommendpic where recommendpicId='" + id + "' limit 1");
        if(map==null){
            throw new Exception("弹出推荐图片的数据找不到！请检查该主键是否存在！");
        }
        if(map.get("openid")==null){
            throw new Exception("openid="+id+",微信用户id不存在");
        }
        String openid = String.valueOf(map.get("openid"));
        Map<String, Object> weixininfo = jdbcTemplate.queryForMap("select * from czj_weixininfo where openid='" + openid + "'");
        map.putAll(weixininfo);
        model.addAttribute("entity",map);
        model.addAttribute("weixininfo",weixininfo);

    }

    public void saveWeixininfo(WeixinInfo weixinInfo) {
        Czjweixininfo czjweixininfo = new Czjweixininfo();
        czjweixininfo.setOpenid(weixinInfo.getOpenid());
        czjweixininfo.setNickname(weixinInfo.getNickname());
        czjweixininfo.setSex(weixinInfo.getSex());
        czjweixininfo.setProvince(weixinInfo.getProvince());
        czjweixininfo.setCity(weixinInfo.getCity());
        czjweixininfo.setCountry(weixinInfo.getCountry());
        czjweixininfo.setHeadimgurl(weixinInfo.getHeadimgurl());
        String[] privilege = weixinInfo.getPrivilege();
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < privilege.length; i++){
            sb.append(privilege[i]+";");
        }
        czjweixininfo.setPrivilege(sb.toString());
        czjweixininfo.setUnionid(weixinInfo.getUnionid());
        czjweixininfo.setCreatetime(new Date());
        try {
            int count = jdbcTemplate.queryForObject("select count(*) from czj_weixininfo where openid='"+weixinInfo.getOpenid()+"'",int.class);
            if(count>0){
                updateWeixininfo(czjweixininfo);
            }else{
                insertWeixininfo(czjweixininfo);
            }
            Map map = JSONObject.parseObject(StaticMap.getWeixinInfoJson(czjweixininfo.getOpenid()), Map.class);
            map.put("update", 0);
            StaticMap.getWeixinInfoJson().put(String.valueOf(map.get("openid")), JSONObject.toJSONString(map));
            System.out.println("更新微信信息！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("插入微信信息失败！");
        }
    }

    /**
     * 更新
     * @param czjweixininfo
     */
    public void updateWeixininfo(Czjweixininfo czjweixininfo) {
        StringBuffer sb2 = new StringBuffer();
        sb2.append("update czj_weixininfo set nickname='");
        sb2.append(czjweixininfo.getNickname());
        sb2.append("',sex='");
        sb2.append(czjweixininfo.getSex());
        sb2.append("',province='");
        sb2.append(czjweixininfo.getProvince());
        sb2.append("',city='");
        sb2.append(czjweixininfo.getCity());
        sb2.append("',country='");
        sb2.append(czjweixininfo.getCountry());
        sb2.append("',headimgurl='");
        sb2.append(czjweixininfo.getHeadimgurl());
        sb2.append("',privilege='");
        sb2.append(czjweixininfo.getPrivilege());
        sb2.append("',unionid='");
        sb2.append(czjweixininfo.getUnionid());
        sb2.append("' where openid='");
        sb2.append(czjweixininfo.getOpenid());
        sb2.append("'");
        jdbcTemplate.update(sb2.toString());
    }

    /**
     * 插入新增
     * @param czjweixininfo
     */
    public void insertWeixininfo(Czjweixininfo czjweixininfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuffer sb2 = new StringBuffer();
        sb2.append("insert into czj_weixininfo (openid,nickname,sex,province,city,country,headimgurl,privilege,unionid,createtime) values('");
        sb2.append(czjweixininfo.getOpenid());
        sb2.append("','");
        sb2.append(czjweixininfo.getNickname());
        sb2.append("','");
        sb2.append(czjweixininfo.getSex());
        sb2.append("','");
        sb2.append(czjweixininfo.getProvince());
        sb2.append("','");
        sb2.append(czjweixininfo.getCity());
        sb2.append("','");
        sb2.append(czjweixininfo.getCountry());
        sb2.append("','");
        sb2.append(czjweixininfo.getHeadimgurl());
        sb2.append("','");
        sb2.append(czjweixininfo.getPrivilege());
        sb2.append("','");
        sb2.append(czjweixininfo.getUnionid());
        sb2.append("','");
        sb2.append(sdf.format(czjweixininfo.getCreatetime()));
        sb2.append("')");
        jdbcTemplate.update(sb2.toString());
    }
    public boolean createFileDir(String destFileDirName) {
        return createDir(destFileDirName.substring(0,destFileDirName.lastIndexOf("/")));

    }
    public boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
//            System.out.println("创建目录" + destDirName + "失败，目标目录已经存在");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            System.out.println("创建目录" + destDirName + "成功！");
            return true;
        } else {
            System.out.println("创建目录" + destDirName + "失败！");
            return false;
        }
    }

    public void saveRecommendpic(Czjrecommendpic czjrecommendpic, MultipartFile multipartFiles, HttpServletRequest req) throws Exception {
        if(!multipartFiles.isEmpty()){
            String basePath = req.getSession().getServletContext().getRealPath("/");
            String path = basePath+"upload/recommendpic/"+czjrecommendpic.getRecommendpicId()+"-"+ System.currentTimeMillis()+multipartFiles.getOriginalFilename().substring(multipartFiles.getOriginalFilename().lastIndexOf("."));
            createFileDir(path);
            InputStream in = multipartFiles.getInputStream();
            FileOutputStream out = new FileOutputStream(path);
            try {

                IOUtils.copy(in,out);

            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("上传图片失败！");
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

            String picPath = "/"+path.replace(basePath, "");
            czjrecommendpic.setPicPath(picPath);
        }
        if(null==czjrecommendpic.getDisplay()){
            czjrecommendpic.setDisplay(0);
        }
        if(null==czjrecommendpic.getUsetemplate()){
            czjrecommendpic.setUsetemplate(0);
        }
        StringBuffer sb = new StringBuffer();
        sb.append("update czj_xy_recommendpic set title='");
        sb.append(czjrecommendpic.getTitle());
        sb.append("',url='");
        sb.append(czjrecommendpic.getUrl());
        if(StringUtils.isNotBlank(czjrecommendpic.getPicPath())){
            sb.append("',picPath='");
            sb.append(czjrecommendpic.getPicPath());
        }
        sb.append("',display='");
        sb.append(czjrecommendpic.getDisplay());
        sb.append("',usetemplate='");
        sb.append(czjrecommendpic.getUsetemplate());
        sb.append("' where recommendpicId='");
        sb.append(czjrecommendpic.getRecommendpicId());
        sb.append("'");
        System.out.println(sb.toString());
        jdbcTemplate.update(sb.toString());

    }

    /**
     * 得到弹出图片信息
     * @param weixininfo
     * @param req
     * @return
     * @throws Exception
     */
    public Map<String,Object> getByCode(WeixinInfo weixininfo, HttpServletRequest req) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String basePath = req.getRequestURL().substring(0,req.getRequestURL().lastIndexOf(req.getRequestURI()));
        basePath+=req.getContextPath();

        //得到弹出推荐图片模板
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listmap = jdbcTemplate.queryForList("select * from czj_xy_dataresource where code='TCMB'");
        for (Map<String, Object> objectMap : listmap) {
            map.put(String.valueOf(objectMap.get("name")),objectMap.get("value"));
        }
        Map<String, Object> object = new HashMap<String, Object>();
        object.put("url",map.get("url"));
        object.put("picPath",map.get("picPath"));
        object.put("validTime", Integer.valueOf(String.valueOf(map.get("validTime"))));
        object.put("title",map.get("title"));
        object.put("display",map.get("display"));
        if("0".equals(String.valueOf(map.get("display")))||null== String.valueOf(map.get("display"))){
            object.put("display",0);
            return object;
        }
        //得到数据库中自定义用户的推荐图片模板
        List<Map<String, Object>> listmapr = jdbcTemplate.queryForList("select * from czj_xy_recommendpic where openid='" + weixininfo.getOpenid() + "'");
        if(listmapr.size()>0){

            Map<String, Object> mp = listmapr.get(0);
            if(!"1".equals(String.valueOf(mp.get("display")))){
                object.put("display",0);
            }else {
                if (!"1".equals(String.valueOf(mp.get("usetemplate")))) {//不使用模板
                    object.put("url", mp.get("url"));
                    object.put("picPath", mp.get("picPath"));
                    object.put("title", mp.get("title"));
                    Date date = (Date) mp.get("updateDate");
                    if(date==null){
                        jdbcTemplate.update("update czj_xy_recommendpic set updateDate='" + sdf.format(new Date()) + "' where recommendpicId='" + mp.get("recommendpicId") + "'");
                        object.put("display", 1);
                    }else {
                        try {
                            Integer.parseInt(String.valueOf(map.get("interval")));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            throw new Exception("czj_xy_datasource表中 弹出模板（code=TCMB）name=interval 未设置!");
                        }
                        //8分钟还没到
                        if ((System.currentTimeMillis() - date.getTime() - Integer.parseInt(String.valueOf(map.get("interval")))  * 60 * 1000) > 0) {
                            jdbcTemplate.update("update czj_xy_recommendpic set updateDate='" + sdf.format(new Date()) + "' where recommendpicId='" + mp.get("recommendpicId") + "'");
                            object.put("display", 1);
                        } else {//8分钟到
                            object.put("display", 0);
                        }
                    }


                } else {
                    Date date = (Date) mp.get("updateDate");
                    if(date==null){
                        jdbcTemplate.update("update czj_xy_recommendpic set updateDate='" + sdf.format(new Date()) + "' where recommendpicId='" + mp.get("recommendpicId") + "'");
                        object.put("display", 1);
                    }else {
                        try {
                            Integer.parseInt(String.valueOf(map.get("interval")));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            throw new Exception("czj_xy_datasource表中 弹出模板（code=TCMB）name=interval 未设置!");
                        }
                        //分钟
                        if ((System.currentTimeMillis() - date.getTime() - Integer.parseInt(String.valueOf(map.get("interval"))) * 60 * 1000) > 0) {
                            jdbcTemplate.update("update czj_xy_recommendpic set updateDate='" + sdf.format(new Date()) + "' where recommendpicId='" + mp.get("recommendpicId") + "'");
                            object.put("display", 1);

                        } else {//8分钟还没到
                            object.put("display", 0);
                        }
                    }
                }
            }

        }else{
            Czjrecommendpic czjrecommendpic = new Czjrecommendpic();
            czjrecommendpic.setRecommendpicId(UUIDUtils.getUUID());
            czjrecommendpic.setTitle(String.valueOf(map.get("title")));
            czjrecommendpic.setUrl(String.valueOf(map.get("url")));
            czjrecommendpic.setOpenid(weixininfo.getOpenid());
            czjrecommendpic.setPicPath(String.valueOf(map.get("picPath")));
            czjrecommendpic.setDisplay(1);
            czjrecommendpic.setCreatetime(new Date());
            czjrecommendpic.setUpdateDate(new Date());
            czjrecommendpic.setUsetemplate(1);
            insert(czjrecommendpic);
            object.put("display","1");

        }
        if(String.valueOf(object.get("picPath"))!=null){
           if(String.valueOf(object.get("picPath")).startsWith("/upload/")){
               basePath+= String.valueOf(object.get("picPath"));
               object.put("picPath", basePath);
           }
        }
        return object;
    }

    public WeixinInfo getWeixinUserinfo(String code,String appid,String secret) throws Exception {
        //得到用户信息
        WeixinInfo weixinInfo = weixininfoService.getWeixinInfo(code, appid, secret);
        if(weixinInfo==null){
            throw new Exception("code值失效或者code值不正确！");
        }
        if(weixinInfo.getUpdate()!=null&&weixinInfo.getUpdate()==1){
            saveWeixininfo(weixinInfo);
        }
        return weixinInfo;
    }
    public void update(Czjrecommendpic czjrecommendpic){
        recommendpicMapper.update(czjrecommendpic);
    }
    public void insert(Czjrecommendpic czjrecommendpic) throws Exception {

        recommendpicMapper.insert(czjrecommendpic);

    }

    public Map<String,Object> getTemplate() {
        List<Map<String, Object>> listmap = jdbcTemplate.queryForList("select * from czj_xy_dataresource where code='TCMB'");
        Map<String, Object> map = new HashMap<String, Object>();
        for (Map<String, Object> objectMap : listmap) {
            map.put(String.valueOf(objectMap.get("name")),objectMap.get("value"));
        }
        return map;
    }

    public void saveTemplate(String url, String validTime, String title, String interval, String display, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
        String picPath = null;
        String basePath = req.getSession().getServletContext().getRealPath("/");
        if(!multipartFile.isEmpty()){

            String path = basePath+"upload/recommendpic/"+UUIDUtils.getDateUUID()+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            createFileDir(path);
            InputStream in = multipartFile.getInputStream();
            FileOutputStream out = new FileOutputStream(path);
            try {

                IOUtils.copy(in,out);

            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("上传图片失败！");
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

            picPath = "/"+path.replace(basePath, "");

        }
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listmap = jdbcTemplate.queryForList("select * from czj_xy_dataresource where code='TCMB'");

        for (Map<String, Object> objectMap : listmap) {
            map.put(String.valueOf(objectMap.get("name")),objectMap.get("value"));
        }
        if(map.containsKey("picPath")){
            if(StringUtils.isNotBlank(picPath)){
                jdbcTemplate.update("update czj_xy_dataresource set value='"+picPath+"' where code='TCMB' and name='picPath'");
            }

        }else{
            jdbcTemplate.execute(" INSERT INTO czj_xy_dataresource (dataresourceId, code, name, value, title, createtime, updatetime, codename) VALUES ('tJSpDeLMP9qw6fZY682', 'TCMB', 'picPath', '"+picPath+"', '默认图片', '2017-05-16 09:46:50', '2017-05-16 09:46:53', '弹出模板')");
        }
        if(map.containsKey("url")){
            jdbcTemplate.update("update czj_xy_dataresource set value='"+url+"' where code='TCMB' and name='url'");
        }else{
            jdbcTemplate.execute(" INSERT INTO czj_xy_dataresource (dataresourceId, code, name, value, title, createtime, updatetime, codename) VALUES ('tJSpDeLMP9qw6fZY18t', 'TCMB', 'url', '"+url+"', '外链接', '2017-05-16 09:46:50', '2017-05-16 09:46:53', '弹出模板')");
        }
        if(map.containsKey("validTime")){
            jdbcTemplate.update("update czj_xy_dataresource set value='"+validTime+"' where code='TCMB' and name='validTime'");
        }else{
            jdbcTemplate.execute("INSERT INTO czj_xy_dataresource (dataresourceId, code, name, value, title, createtime, updatetime, codename) VALUES ('tnOPsfV6nr3xEsiUWRP', 'TCMB', 'validTime', '"+validTime+"', '弹出时间', '2017-05-16 09:52:15', '2017-05-16 09:52:12', '弹出模板')");
        }
        if(map.containsKey("title")){
            jdbcTemplate.update("update czj_xy_dataresource set value='"+title+"' where code='TCMB' and name='title'");
        }else{
            jdbcTemplate.execute("INSERT INTO czj_xy_dataresource (dataresourceId, code, name, value, title, createtime, updatetime, codename) VALUES ('pf5y7l7VZHTkN6BqaEB', 'TCMB', 'title', '"+title+"', '弹出框标题', '2017-05-16 09:53:56', '2017-05-16 09:53:58', '弹出模板')");
        }
        if(map.containsKey("interval")){
            jdbcTemplate.update("update czj_xy_dataresource set value='"+interval+"' where code='TCMB' and name='interval'");
        }else{
            jdbcTemplate.execute("INSERT INTO czj_xy_dataresource (dataresourceId, code, name, value, title, createtime, updatetime, codename) VALUES ('VRhkHKje3afxpqnT2kB', 'TCMB', 'interval', '"+interval+"', '弹出间隔时间', '2017-05-16 16:34:19', '2017-05-16 16:34:23', '弹出模板')");
        }

        if("1".equals(display)) {
            if (map.containsKey("display")) {
                jdbcTemplate.update("update czj_xy_dataresource set value='" + display + "' where code='TCMB' and name='display'");
            } else {
                jdbcTemplate.execute("INSERT INTO czj_xy_dataresource (dataresourceId, code, name, value, title, createtime, updatetime, codename) VALUES ('5yhLqWC9BXbLEuKubUn', 'TCMB', 'display', '" + display + "', '默认全局显示或隐藏', '2017-05-16 16:34:19', '2017-05-16 16:34:23', '弹出模板')");
            }
        }else{
            display = "0";
            if (map.containsKey("display")) {
                jdbcTemplate.update("update czj_xy_dataresource set value='" + display + "' where code='TCMB' and name='display'");
            } else {
                jdbcTemplate.execute("INSERT INTO czj_xy_dataresource (dataresourceId, code, name, value, title, createtime, updatetime, codename) VALUES ('5yhLqWC9BXbLEuKubUn', 'TCMB', 'display', '" + display + "', '默认全局显示或隐藏', '2017-05-16 16:34:19', '2017-05-16 16:34:23', '弹出模板')");
            }
        }
    }
}
